package com.youlai.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.util.DateUtils;
import com.youlai.system.converter.CourseConverter;
import com.youlai.system.mapper.SysCourseMapper;
import com.youlai.system.model.entity.SysCourse;
import com.youlai.system.model.form.CourseForm;
import com.youlai.system.model.query.CoursePageQuery;
import com.youlai.system.model.vo.CoursePageVO;
import com.youlai.system.service.SysCategoryService;
import com.youlai.system.service.SysCourseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 培训科目业务处理实现
 */
@Service
@RequiredArgsConstructor
public class SysCourseServiceImpl extends ServiceImpl<SysCourseMapper, SysCourse> implements SysCourseService {

    private final CourseConverter courseConverter;

    private final SysCategoryService categoryService;

    @Override
    public SysCourse getByContentEqual(String content) {
        LambdaQueryWrapper<SysCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCourse::getContent, content);
        return getOne(queryWrapper);
    }

    @Override
    public SysCourse saveByContent(String content) {
        SysCourse course = new SysCourse();
        course.setContent(content);
        save(course);
        return course;
    }

    @Override
    public Page<CoursePageVO> getCoursePage(CoursePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        Long categoryId = queryParams.getCategoryId();
        Integer month = queryParams.getMonth();

        LambdaQueryWrapper<SysCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(keywords), SysCourse::getContent, keywords);
        queryWrapper.eq(categoryId != null, SysCourse::getCategoryId, categoryId);
        queryWrapper.eq(month != null, SysCourse::getMonth, month).orderByAsc(SysCourse::getCategoryId);
        //查询数据
        Page<SysCourse> coursePage = this.page(new Page<>(pageNum, pageSize), queryWrapper);

        //设置分类
        List<Option> categoryList = categoryService.listCategoryOptions();
        Map<Long, Option> categoryMap = categoryList.stream().collect(Collectors.toMap(Option<Long>::getValue, it -> it));
        coursePage.getRecords().forEach(course -> {
            Option option = categoryMap.get(course.getCategoryId());
            if (option != null) {
                course.setCategoryName(option.getLabel());
            }
        });

        //设置日期
        coursePage.getRecords().forEach(course -> {
            course.setMonthName(DateUtils.monthTranslate(course.getMonth()));
        });
        return courseConverter.entity2Page(coursePage);
    }

    @Override
    public boolean saveCourse(CourseForm courseForm) {
        String content = courseForm.getContent();

        long count = this.count(new LambdaQueryWrapper<SysCourse>().eq(SysCourse::getContent, content));
        Assert.isTrue(count == 0, "故障已存在");

        // 实体转换
        SysCourse course = courseConverter.form2Entity(courseForm);
        return save(course);
    }

    @Override
    public boolean updateCourse(Long courseId, CourseForm courseForm) {
        String content = courseForm.getContent();

        long count = this.count(new LambdaQueryWrapper<SysCourse>()
                .eq(SysCourse::getContent, content)
                .ne(SysCourse::getId, courseId)
        );
        Assert.isTrue(count == 0, "故障已存在");

        // form -> entity
        SysCourse entity = courseConverter.form2Entity(courseForm);

        // 修改故障
        return this.updateById(entity);
    }

    @Override
    public CourseForm getCourseForm(Long courseId) {
        SysCourse entity = this.getById(courseId);
        return courseConverter.entity2Form(entity);
    }

    @Override
    public boolean deleteCourses(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "故障删除数据为空");
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(ids);
    }

    @Override
    public boolean deleteCourses(List<Long> idList) {
        return this.removeByIds(idList);
    }

    @Override
    public List<Option> listCourseOptions() {
        // 查询数据
        List<SysCourse> courseList = this.list(new LambdaQueryWrapper<SysCourse>()
                .select(SysCourse::getId, SysCourse::getContent)
                .orderByAsc(SysCourse::getSort)
        );

        // 实体转换
        return courseConverter.entities2Options(courseList);
    }

    @Override
    public List<SysCourse> getCategoryCourseCountList() {
        QueryWrapper<SysCourse> queryWrapper  = Wrappers.query();
        queryWrapper.select("category_id", "count(*) as courseCount", "GROUP_CONCAT(content) as groupCourseName").isNotNull("category_id").groupBy("category_id");
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public Map<Long, SysCourse> getCategoryCourseCountMap() {
        return getCategoryCourseCountList().stream().collect(Collectors.toMap(SysCourse::getCategoryId, it -> it));
    }

    @Override
    public boolean categoryHasUsed(List<Long> categoryIdList) {
        LambdaQueryWrapper<SysCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysCourse::getCategoryId, categoryIdList);
        return count(queryWrapper) > 0;
    }

    @Override
    public List<Long> idList() {
        LambdaQueryWrapper<SysCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysCourse::getId);
        return list(queryWrapper).stream().map(SysCourse::getId).collect(Collectors.toList());
    }
}
